﻿using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.Dtos.Versions;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace IM.Easy.SystemServices.Mapper
{
    public class ReleaseMapper : IRegister
    {
        public void Register(TypeAdapterConfig config)
        {
            string pattern = @"^(\d+)\.(\d+)\.(\d+)(.*)$";

            config.ForType<ReleaseLogDto, ReleaseLog>()
                .AfterMapping((src, dest) =>
                {
                    // 初始化默认值
                    dest.Major = 0;
                    dest.Minor = 0;
                    dest.Patch = 0;
                    dest.Suffix = null;

                    if (string.IsNullOrEmpty(src.VersionCode))
                        return;

                    var match = Regex.Match(src.VersionCode, pattern);
                    if (!match.Success)
                        throw new Exception("版本号格式应为 x.x.x");

                    if (int.TryParse(match.Groups[1].Value, out int major))
                    {
                        dest.Major = major;
                    }

                    if (int.TryParse(match.Groups[2].Value, out int minor))
                    {
                        dest.Minor = minor;
                    }

                    if (int.TryParse(match.Groups[3].Value, out int patch))
                    {
                        dest.Patch = patch;
                    }

                    // 处理后缀
                    var suffix = match.Groups[4].Value.Trim();
                    dest.Suffix = string.IsNullOrEmpty(suffix) ? null : suffix;
                });

            config.ForType<ReleaseLog, ReleaseLogDto>()
                    .AfterMapping((src, dest) =>
                    {
                        var baseVersion = $"{src.Major}.{src.Minor}.{src.Patch}";
                        if (!string.IsNullOrEmpty(src.Suffix))
                        {
                            dest.VersionCode = $"{baseVersion}{src.Suffix}";
                        }
                        else
                        {
                            dest.VersionCode = baseVersion;
                        }
                    });
        }
    }
}
